package com.niit.service.impl;

import com.niit.entity.Menu;
import com.niit.repository.MenuRepository;
import com.niit.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {

	@Autowired
	private MenuRepository menuRepository;

	@Override
	public List<Menu> getAllMenu() {
		List<Menu> menus = menuRepository.findAll(Sort.by(Sort.Direction.ASC, "order"));
		return buildMenuTree(menus);
	}

	private List<Menu> buildMenuTree(List<Menu> menus) {
		// 使用Map存储所有菜单（ID -> Menu对象）
		Map<Integer, Menu> menuMap = menus.stream()
				.collect(Collectors.toMap(Menu::getId, menu -> menu));

		List<Menu> rootMenus = new ArrayList<>();

		for (Menu menu : menus) {
			Integer parentId = menu.getParentId();
			if (parentId == null || parentId == 0) {
				rootMenus.add(menu);
			} else {
				// 找到父菜单并添加当前菜单作为子项
				Menu parent = menuMap.get(parentId);
				if (parent != null) {
					parent.getChildren().add(menu);
				}
			}
		}

		// 对子菜单排序
		for (Menu menu : menus) {
			menu.setChildren(sortChildren(menu.getChildren()));
		}

		// 对根菜单排序
		rootMenus.sort(Comparator.comparing(Menu::getOrder));
		return rootMenus;
	}

	private List<Menu> sortChildren(List<Menu> children) {
		if (children == null || children.isEmpty()) {
			return children;
		}
		return children.stream()
				.sorted(Comparator.comparing(Menu::getOrder))
				.collect(Collectors.toList());
	}


}
